package com.codeos.khttp.request.body;

import com.codeos.khttp.utils.KHttpUtils;

import java.io.*;

public class KBodyItemFile implements KBodyItem {

    private StringBuffer mHttpHeader = new StringBuffer();
    private File mFile;

    public KBodyItemFile(String name, File file, String properties) {

        // 参数判断
        if(file == null) {
            throw new IllegalStateException("please set input file!");
        }

        if(file.exists() == false) {
            throw new IllegalStateException("file not exist!");
        }

        mFile = file;

        if(name == null) {
            name = "file";
        }

        String realFileName = file.getName();
        int dotIndex = file.getName().lastIndexOf(".");
        String ext = realFileName.substring(dotIndex);

        switch(ext) {
            case ".jpg":
            case ".jpeg":
                if(properties == null) {
                    mHttpHeader.append("Content-Disposition: form-data; name=\""+name+"\n\"; filename=\""+realFileName+"\""+ KHttpUtils.gHttpEnd);
                } else {
                    mHttpHeader.append("Content-Disposition: form-data; name=\""+name+"\n\"; filename=\""+realFileName+"\"; "+properties+";" + KHttpUtils.gHttpEnd);
                }
                mHttpHeader.append("Content-Type: image/jpeg" + KHttpUtils.gHttpEnd);
                break;
            default:
                throw new IllegalArgumentException("not supported file format!("+realFileName+")");
        }
        mHttpHeader.append(KHttpUtils.gHttpEnd);
    }
    @Override
    public int getItemLength() {
        return mHttpHeader.length() + (int)mFile.length() + KHttpUtils.gHttpEnd.length();
    }

    @Override
    public void sendItemData(OutputStream os, OutputStreamWriter writer) throws IOException {

        FileInputStream fis = new FileInputStream(mFile);

        writer.write(mHttpHeader.toString());
        writer.flush();
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        writer.flush();
        writer.write(KHttpUtils.gHttpEnd);

        fis.close();
    }

    @Override
    public String toString() {
        return mHttpHeader.toString()+"[File] length="+mFile.length()+KHttpUtils.gHttpEnd;
    }
}
